//=============================================================================
// EmptyApp GP1 by Bart Uyttenhove
//=============================================================================
#include "StdAfx.h"
#include "EmptyApp.h"
#include "ContentManager.h"
#include "InputStateManager.h"
#include "RenderContext.h"
#include "Level.h"
#include "GraphCamera.h"
#include "Camera.h"
#include "BaseCamera.h"
#include "Character.h"
#include "DX10ObjMesh.h"
#include "ObjMesh.h"
#include "IniFile.h"
#include "ObjReader.h"
#include "PhysicsMesh.h"
#include "LightReader.h"
#include "SpherePNT.h"
#include "SimpleBone.h"
#include "SoftwareSkinMesh.h"
#include "BinAnimationReader.h"
#include "FullScreenQuad.h"
#include "DrawableTex2D.h"
#include <cmath>
#include "SpikeySphere.h"
#include "ShadowCamera.h"
#include "PhysX.h"
#include "Math.h"
#include "MiniMap.h"
#include "Interface.h"
#include "InterfaceItems.h"
#include "PhysicsDebugRenderer.h"
#include "Terrain.h"
#include "SkyBox.h"
#include "QuadPNT.h"
#include "SearchCell.h"
#include "PathFinding.h"
#include "Building.h"
#include "Soldier.h"
#include "AI.h"

#ifdef _DEBUG
#endif

#define BUTTONWIDTH 0.125f
#define BUTTONHEIGHT 0.3f

#pragma comment(lib, "winmm.lib")
#pragma comment(lib, "libexpatw.lib")
#pragma comment(lib, "objReader.lib")

EmptyApp::EmptyApp(HINSTANCE hInstance)
	: D3DApp(hInstance)
	,m_pContentManager(0)
	,m_pLevel(0)
	,m_iCameraNumber(1)
	,m_Triggered(false)
	,m_FullScreenQuad(0)
	,m_IsPathfindig(false)
	,m_LeftMouseUp(true)
	,m_RightMouseUp(true)
	,m_PlaceBuilding(false)
	,m_BuildingSelected(false)
	,m_IdSelected(0)
	,m_Money(5000)
	,m_CostPrice(0)
	,m_MaxNumberSoldiers(0)
	,m_IsSelectingSoldiers(false)
	,m_TheEnd(false)
	,m_GotMain(true)


#ifdef _DEBUG
	,m_pPhysicsDebugRenderer(0)
	,m_renderstate(Normal)
#endif
{

}

EmptyApp::~EmptyApp()
{
	SafeDelete(m_pContentManager);
	SafeDelete(m_pLevel);	
	SafeDelete(m_FullScreenQuad);
	SafeDelete(m_pShadowCam);
	SafeDelete(m_refInputState);

#ifdef _DEBUG
	SafeDelete(m_pPhysicsDebugRenderer);
#endif

}
void EmptyApp::SetWindowParams()
{
	m_MainWndCaption = _T("D3D10 Test Application");
	m_ClientWidth = 1280; //640
	m_ClientHeight = 960; //480
}

bool EmptyApp::InitGame()
{
	//Contentmanager loads effects, textures
	m_pContentManager = new ContentManager();

	//ShowCursor(false);
	
	m_pLevel = new Level(m_pD3DDevice);

	m_AI = new AI(m_pContentManager, m_pLevel);

	LoadMeshes();
	LoadInterface();

	m_FullScreenQuad = new FullScreenQuad(m_pContentManager, m_pD3DDevice, _T("./Effect/ShadowMapTester.fx"));
	m_FullScreenQuad->Initialize(m_pContentManager);

	m_PostProces = new DrawableTex2D(m_pD3DDevice);
	m_PostProces->Init(m_ClientWidth, m_ClientHeight, true, DXGI_FORMAT_R8G8B8A8_UNORM);

	m_pGraphCamera = new GraphCamera(64, 48);
	m_pGraphCamera->LookAt(D3DXVECTOR3(0, 70, -70), D3DXVECTOR3(0, 0, 0), D3DXVECTOR3(0, 1, 0));
	m_pLevel->AddChild(m_pGraphCamera);

	m_MiniMapCamera = new GraphCamera(m_ClientWidth, m_ClientHeight);
	m_MiniMapCamera->LookAt(D3DXVECTOR3(0,270, 0),D3DXVECTOR3(0,0,0),D3DXVECTOR3(0,0,1));
	m_MiniMapCamera->SetStacic();
	m_pLevel->AddChild(m_MiniMapCamera);

	m_pLevel->AddChild(new SkyBox(_T("./Resources/SkyBox Terrain/SnowLandscape1024DXtoolmade.dds")));

	//After initialization, the actors exist and the joints can be created
	m_MiniMap = new MiniMap(m_pContentManager, m_pD3DDevice, _T("./Effect/ShadowMapTester.fx"));
	m_MiniMap->Initialize(m_pContentManager);

	m_pLevel->Initialize(m_pContentManager);

	m_Buildinglist.at(0)->Scale(D3DXVECTOR3(0.2f,0.2f,0.2f));
	m_Buildinglist.at(0)->Translate(D3DXVECTOR3(D3DXVECTOR3(-80, 0, -80)));
	m_Buildinglist.at(0)->SetTriggerPos(D3DXVECTOR3(-80, 0, -80));

	m_Energylist.at(0)->Scale(D3DXVECTOR3(0.4,0.4,0.4));
	m_Energylist.at(0)->Translate(D3DXVECTOR3(100, 0, 100));
	m_Energylist.at(0)->SetTriggerPos(D3DXVECTOR3(0, 0, 0));

	m_Energylist.at(1)->Scale(D3DXVECTOR3(0.4,0.4,0.4));
	m_Energylist.at(1)->Translate(D3DXVECTOR3(-100, 0, -100));
	m_Energylist.at(1)->SetTriggerPos(D3DXVECTOR3(0, 0, 0));

	m_MakePath = new PathFinding(m_pLevel);


#ifdef _DEBUG
	//put this after level initialization
	m_pPhysicsDebugRenderer = new PhysicsDebugRenderer(m_pLevel);
	m_pPhysicsDebugRenderer->Initialize(m_pContentManager);
#endif

	//Light
	m_DirLight.DirW = D3DXVECTOR3(0.2f,-0.2f,0.6f);
	D3DXVec3Normalize(&m_DirLight.DirW, &m_DirLight.DirW);
	m_DirLight.Diffuse = m_DirLight.Ambient = m_DirLight.Specular = D3DXCOLOR(1.0f,1.0f,1.0f,1.0f);
	return true;
}

bool EmptyApp::OnGameWindowResized()
{
	if(m_pLevel)m_pLevel->OnResize(m_ClientWidth, m_ClientHeight);

	return true;
}

void EmptyApp::UpdateScene(const InputState & refInputState)
{	
	if(m_TheEnd == false)
	{
		m_AI->SetEnemyBuildingList(m_Buildinglist);
		m_AI->SetEnemySoldierList(m_Soldierlist);
		m_AI->Tick(refInputState);

		for(int i = 0; m_Soldierlist.size() > i ; ++i)
		{
			if(m_Soldierlist.at(i)->GetDeleted())
			{
					m_Soldierlist.at(i)->RemoveSphere();

					m_Soldierlist.at(i)->SetParent(NULL);

					vector<Soldier*>::iterator foundElement;
					foundElement = std::find(m_Soldierlist.begin(),m_Soldierlist.end(),m_Soldierlist.at(i));
					if ( foundElement != m_Soldierlist.end())
					{
							m_Soldierlist.erase(foundElement);
					}
			}
		}

		for(int i = 0; m_Buildinglist.size() > i ; ++i)
		{
			if(m_Buildinglist.at(i)->GetDeleted())
			{
					if(m_Buildinglist.at(m_IdSelected) == m_Buildinglist.at(i))
					{
						m_BuildingSelected = false;

						if(m_Buildinglist.at(i)->GetMesh() == m_BarracksMesh)
						{
							m_HudItems.at(0)->SetTexture(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/Main.jpg")));
							m_HudItems.at(1)->SetOpacity(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/Zero.jpg")));
							m_HudItems.at(2)->SetOpacity(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/Zero.jpg")));
							m_HudItems.at(3)->SetOpacity(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/Zero.jpg")));
						}
					}

					if(m_Buildinglist.at(i)->GetMesh() == m_HarvesterMesh)
					{
						D3DXVECTOR4 pos;
						D3DXVec3Transform(&pos, &D3DXVECTOR3(0, 0, 0), &m_Buildinglist.at(i)->GetWorldMatrix());

						for(int i = 0; m_Harvesterlist.size() > i ; ++i)
						{
							D3DXVECTOR3 home = m_Harvesterlist.at(i)->m_PosHome;
							if(pos.x == home.x && (pos.z- 8) == home.z )
							{
								m_pLevel->RemoveChild(m_Harvesterlist.at(i));

								vector<SpikeySphere*>::iterator foundElement;
								foundElement = std::find(m_Harvesterlist.begin(),m_Harvesterlist.end(),m_Harvesterlist.at(i));
								if ( foundElement != m_Harvesterlist.end())
								{
										m_Harvesterlist.erase(foundElement);
								}

								vector<PathFinding*>::iterator foundElement2;
								foundElement2 = std::find(m_HarvesterPathList.begin(),m_HarvesterPathList.end(),m_HarvesterPathList.at(i));
								if ( foundElement2 != m_HarvesterPathList.end())
								{
										m_HarvesterPathList.erase(foundElement2);
								}
							}
						}			
					}

					if(m_Buildinglist.at(i)->GetMesh() == m_HouseMesh) m_MaxNumberSoldiers -= 3; 

					if(m_Buildinglist.at(i)->GetMesh() == m_MainMesh) m_GotMain = false; 

					m_Buildinglist.at(i)->RemoveThis();

					m_Buildinglist.at(i)->SetParent(NULL);

					vector<Building*>::iterator foundElement;
					foundElement = std::find(m_Buildinglist.begin(),m_Buildinglist.end(),m_Buildinglist.at(i));
					if ( foundElement != m_Buildinglist.end())
					{
							m_Buildinglist.erase(foundElement);
					}
			}
		}

		m_AI->CheckForRemove();

		POINTS Position = refInputState.GetMousePos();

			float Xndc = (float)(Position.x - (m_ClientWidth/2)) / (m_ClientWidth/2);
			float Yndc = (float)((m_ClientHeight/2) - Position.y) / (m_ClientHeight/2);

			D3DXMATRIX invers;
			D3DXMatrixInverse(&invers, NULL, &m_pGraphCamera->GetViewProj());

			D3DXVECTOR3 Nearplane(Xndc,Yndc, 0);
			D3DXVECTOR3 Farplane(Xndc, Yndc, 1);

			D3DXVECTOR3 NearplaneInv;
			D3DXVECTOR3 FarplaneInv;

			D3DXVec3TransformCoord(&NearplaneInv, &Nearplane, &invers);
			D3DXVec3TransformCoord(&FarplaneInv, &Farplane, &invers);

			NxVec3 direction(FarplaneInv.x - NearplaneInv.x, FarplaneInv.y - NearplaneInv.y, FarplaneInv.z - NearplaneInv.z);		

			NxRay Raycast;

			Raycast.orig = NxVec3(NearplaneInv.x, NearplaneInv.y, NearplaneInv.z);
			Raycast.dir = NxVec3(FarplaneInv.x, FarplaneInv.y, FarplaneInv.z) - NxVec3(NearplaneInv.x, NearplaneInv.y, NearplaneInv.z);
			Raycast.dir.normalize();

			NxRaycastHit GetIntercect;

			NxShape* ClosestShape = m_pLevel->GetPhysicsScene()->raycastClosestShape(Raycast, NX_ALL_SHAPES, GetIntercect);

			if(ClosestShape)
			{
				TestY = GetIntercect.worldImpact.y;
			}
	

		if(m_PlaceBuilding == true)
		{
			POINTS Position = refInputState.GetMousePos();

			float Xndc = (float)(Position.x - (m_ClientWidth/2)) / (m_ClientWidth/2);
			float Yndc = (float)((m_ClientHeight/2) - Position.y) / (m_ClientHeight/2);

			D3DXMATRIX invers;
			D3DXMatrixInverse(&invers, NULL, &m_pGraphCamera->GetViewProj());

			D3DXVECTOR3 Nearplane(Xndc,Yndc, 0);
			D3DXVECTOR3 Farplane(Xndc, Yndc, 1);

			D3DXVECTOR3 NearplaneInv;
			D3DXVECTOR3 FarplaneInv;

			D3DXVec3TransformCoord(&NearplaneInv, &Nearplane, &invers);
			D3DXVec3TransformCoord(&FarplaneInv, &Farplane, &invers);

			NxVec3 direction(FarplaneInv.x - NearplaneInv.x, FarplaneInv.y - NearplaneInv.y, FarplaneInv.z - NearplaneInv.z);		

			NxRay Raycast;

			Raycast.orig = NxVec3(NearplaneInv.x, NearplaneInv.y, NearplaneInv.z);
			Raycast.dir = NxVec3(FarplaneInv.x, FarplaneInv.y, FarplaneInv.z) - NxVec3(NearplaneInv.x, NearplaneInv.y, NearplaneInv.z);
			Raycast.dir.normalize();

			NxRaycastHit GetIntercect;

			NxShape* ClosestShape = m_pLevel->GetPhysicsScene()->raycastClosestShape(Raycast, NX_ALL_SHAPES, GetIntercect);

			if(ClosestShape)
			{
				D3DXVECTOR3 newpos = D3DXVECTOR3(GetIntercect.worldImpact.x, GetIntercect.worldImpact.y, GetIntercect.worldImpact.z);

				D3DXVECTOR4 pos;
				D3DXVec3Transform(&pos, &D3DXVECTOR3(0, 0, 0), &m_Buildinglist.back()->GetWorldMatrix());

				NxVec3 distance = NxVec3(newpos.x, 3, newpos.z) - NxVec3(pos.x, 3, pos.z);

				m_Buildinglist.back()->Translate(D3DXVECTOR3(distance.x, 0, distance.z));
				m_Buildinglist.back()->SetTriggerPos(newpos);
			}
		}
			if(refInputState.IsLeftMouseButtonDown() && m_LeftMouseUp == true)
			{
				m_LeftMouseUp = false;
				m_MousPosRect.x = refInputState.GetMousePos().x;
				m_MousPosRect.y = refInputState.GetMousePos().y;
			}

			if(refInputState.IsLeftMouseButtonDown() && m_LeftMouseUp == false)
			{
				if(m_MousPosRect.x < refInputState.GetMousePos().x - 10 || m_MousPosRect.x > refInputState.GetMousePos().x + 10 ||
					m_MousPosRect.y < refInputState.GetMousePos().y - 10 || m_MousPosRect.y > refInputState.GetMousePos().y+ 10)
				{
					m_IsSelectingSoldiers = true;

					m_SelectRect->SetOpacity(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/SelectOp.jpg")));

					float Xndc = (float)(m_MousPosRect.x - (m_ClientWidth/2)) / (m_ClientWidth/2);
					float Yndc = (float)((m_ClientHeight/2) - m_MousPosRect.y) / (m_ClientHeight/2);
				

					float newXndc = (float)(refInputState.GetMousePos().x - (m_ClientWidth/2)) / (m_ClientWidth/2);
					float newYndc = (float)((m_ClientHeight/2) - refInputState.GetMousePos().y) / (m_ClientHeight/2);

					if((Xndc < newXndc && Yndc > newYndc) || (Xndc > newXndc && Yndc < newYndc))
					{
						m_SelectRect->SetPos(D3DXVECTOR2(Xndc, Yndc));
						m_SelectRect->SetWidth(-(Xndc - newXndc));
						m_SelectRect->SetHeight(Yndc - newYndc);				
					}

					else if(Xndc > newXndc && Yndc > newYndc)
					{
						m_SelectRect->SetPos(D3DXVECTOR2(newXndc, Yndc));
						m_SelectRect->SetWidth((Xndc - newXndc));
						m_SelectRect->SetHeight(Yndc - newYndc);
					}

					else if(Xndc < newXndc && Yndc < newYndc)
					{
						m_SelectRect->SetPos(D3DXVECTOR2(Xndc, newYndc));
						m_SelectRect->SetWidth(-(Xndc - newXndc));
						m_SelectRect->SetHeight(-(Yndc - newYndc));
					}

					m_SelectRect->SetNewRect();			
				}
			}

			if(!refInputState.IsLeftMouseButtonDown() && m_LeftMouseUp == false)
			{			
				for(int i = 0; m_Soldierlist.size() > i ; ++i)
				{
					m_Soldierlist.at(i)->SetOpacity(1);
				}
			
				if(m_IsSelectingSoldiers == true)
				{
					m_SelectRect->SetOpacity(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/one.jpg")));

					for(int i = 0; m_Soldierlist.size() > i; ++i)
					{
						D3DXVECTOR4 pos;
						D3DXVec3Transform(&pos, &D3DXVECTOR3(0, 0, 0), &m_Soldierlist.at(i)->GetWorldMatrix());
						D3DXVECTOR3 t(pos.x, pos.y, pos.z);
						D3DXVECTOR3 projected ;
						D3DXVec3TransformCoord(&projected, &t, &m_pGraphCamera->GetViewProj());

						float Xndc = (float)(m_MousPosRect.x - (m_ClientWidth/2)) / (m_ClientWidth/2);
						float Yndc = (float)((m_ClientHeight/2) - m_MousPosRect.y) / (m_ClientHeight/2);
				

						float newXndc = (float)(refInputState.GetMousePos().x - (m_ClientWidth/2)) / (m_ClientWidth/2);
						float newYndc = (float)((m_ClientHeight/2) - refInputState.GetMousePos().y) / (m_ClientHeight/2);

						if((Xndc < newXndc && Yndc > newYndc))
						{
							if((projected.x > Xndc && projected.x < newXndc) && (projected.y < Yndc && projected.y > newYndc))
							{
								m_Soldierlist.at(i)->SetOpacity(0.5f);
							}
						}

						else if(Xndc > newXndc && Yndc > newYndc)
						{
							if((projected.x < Xndc && projected.x > newXndc) && (projected.y < Yndc && projected.y > newYndc))
							{
								m_Soldierlist.at(i)->SetOpacity(0.5f);
							}
						}

						else if(Xndc < newXndc && Yndc < newYndc)
						{
							if((projected.x > Xndc && projected.x < newXndc) && (projected.y > Yndc && projected.y < newYndc))
							{
								m_Soldierlist.at(i)->SetOpacity(0.5f);
							}
						}

						else if(Xndc > newXndc && Yndc < newYndc)
						{
							if((projected.x < Xndc && projected.x > newXndc) && (projected.y > Yndc && projected.y < newYndc))
							{
								m_Soldierlist.at(i)->SetOpacity(0.5f);
							}
						}				
					}

					m_IsSelectingSoldiers = false;
				}

				else
				{
					LeftMouse(refInputState);
				}

				m_LeftMouseUp = true;
			
			}	

			if(refInputState.IsRightMouseButtonDown())
			{
				m_RightMouseUp = false;
			}

			if(!refInputState.IsRightMouseButtonDown() && m_RightMouseUp == false)
			{	
				RightMouse(refInputState);

				m_RightMouseUp = true;
			}	

			for(int i = 0; i < m_Harvesterlist.size(); ++i)
			{
				if(m_Harvesterlist.at(i)->m_GotPath == false)
				{
					if(m_HarvesterPathList.at(i)->m_foundGoal == false)
					{				
						D3DXVECTOR4 pos;
						D3DXVec3Transform(&pos, &D3DXVECTOR3(0, 0, 0), &m_Harvesterlist.at(i)->GetWorldMatrix());

						if(m_Harvesterlist.at(i)->m_Home == true)	m_HarvesterPathList.at(i)->FindPath(D3DXVECTOR3(pos.x, 3, pos.z), D3DXVECTOR3(-100, 3, -95));
						else	m_HarvesterPathList.at(i)->FindPath(D3DXVECTOR3(-100, 3, -95), D3DXVECTOR3(m_Harvesterlist.at(i)->m_PosHome.x, 3, m_Harvesterlist.at(i)->m_PosHome.z));
					}

					if(m_HarvesterPathList.at(i)->m_foundGoal == true)
					{
						m_Harvesterlist.at(i)->SetPath(m_HarvesterPathList.at(i)->GetPath());
						m_Harvesterlist.at(i)->m_GotPath = true;
					}
				}

				else
				{
					m_Harvesterlist.at(i)->Move();
				}	

				if(m_Harvesterlist.at(i)->m_GotDestination == true)
				{
					m_Harvesterlist.at(i)->SetHome();
					if(m_Harvesterlist.at(i)->m_Home == true) m_Money += 25;
					m_Harvesterlist.at(i)->m_GotPath = false;
					m_Harvesterlist.at(i)->m_GotDestination = false;
					m_HarvesterPathList.at(i) = new PathFinding(m_pLevel);
				}
			}

			for(int i = 0; m_Soldierlist.size() > i; ++i)
			{
				m_Soldierlist.at(i)->Move();
			}

			vector <Building*> Buildings = m_AI->GetBuildingList();
			vector <Soldier*> Soldiers = m_AI->GetSoldierList();
			vector <vector <Soldier*>> Attackers = m_AI->GetSoldierAttackingList();

			for(int i = 0; m_Soldierlist.size() > i; ++i)
			{
				D3DXVECTOR4 posSol;
				D3DXVec3Transform(&posSol, &D3DXVECTOR3(0, 0, 0), &m_Soldierlist.at(i)->GetWorldMatrix());	

				if(m_Soldierlist.at(i)->FoundTargetToAttack() == false && m_Soldierlist.at(i)->GetPath().size() == 0)
				{
					if(m_Soldierlist.at(i)->FoundTargetToAttack() == false )
					{
						for(int j = 0; Soldiers.size() > j; ++j)
						{
							D3DXVECTOR4 pos;
							D3DXVec3Transform(&pos, &D3DXVECTOR3(0, 0, 0), &Soldiers.at(j)->GetWorldMatrix());	

							D3DXVECTOR4 Distance4 = posSol - pos;
							NxVec3 Distance(Distance4.x, Distance4.y, Distance4.z);
							float newLenght = Distance.magnitude();

							if(newLenght <= m_Soldierlist.at(i)->GetRange())
							{
								m_Soldierlist.at(i)->IsAttacking(Soldiers.at(j));
							}
						}
					}

					if(m_Soldierlist.at(i)->FoundTargetToAttack() == false )
					{
						for(int j = 0; Buildings.size() > j; ++j)
						{
							int Width = Buildings.at(j)->GetX();

							D3DXVECTOR4 pos;
							D3DXVec3Transform(&pos, &D3DXVECTOR3(0, 0, 0), &Buildings.at(j)->GetWorldMatrix());	

							D3DXVECTOR4 Distance4 = posSol - pos;
							NxVec3 Distance(Distance4.x, Distance4.y, Distance4.z);
							float newLenght = Distance.magnitude() - Width;

							if(newLenght <= m_Soldierlist.at(i)->GetRange())
							{
								m_Soldierlist.at(i)->IsAttacking(Buildings.at(j));
							}
						}
					}

					if(m_Soldierlist.at(i)->FoundTargetToAttack() == false )
					{
						for(int j = 0; Attackers.size() > j; ++j)
						{
							for(int k = 0; Attackers.at(j).size() > k; ++k)
							{
								D3DXVECTOR4 pos;
								D3DXVec3Transform(&pos, &D3DXVECTOR3(0, 0, 0), &Attackers.at(j).at(k)->GetWorldMatrix());	

								D3DXVECTOR4 Distance4 = posSol - pos;
								NxVec3 Distance(Distance4.x, Distance4.y, Distance4.z);
								float newLenght = Distance.magnitude();

								if(newLenght <= m_Soldierlist.at(i)->GetRange())
								{
									m_Soldierlist.at(i)->IsAttacking(Attackers.at(j).at(k));
								}
							}
						}
					}
				}

				else if(m_Soldierlist.at(i)->FoundTargetToAttack() == false)
				{
					if(m_TargetToAttack != NULL)
					{
						for(int j = 0; Buildings.size() > j; ++j)
						{
							if(Buildings.at(j) == m_TargetToAttack)
							{
								int Width = Buildings.at(j)->GetX();

								D3DXVECTOR4 pos;
								D3DXVec3Transform(&pos, &D3DXVECTOR3(0, 0, 0), &Buildings.at(j)->GetWorldMatrix());	

								D3DXVECTOR4 Distance4 = posSol - pos;
								NxVec3 Distance(Distance4.x, Distance4.y, Distance4.z);
								float newLenght = Distance.magnitude() - Width;

								if(newLenght <= m_Soldierlist.at(i)->GetRange())
								{
									m_Soldierlist.at(i)->IsAttacking(Buildings.at(j));
								}
							}
						}
					}
				}

				else
				{
					m_Soldierlist.at(i)->Attack(refInputState.GetDeltaTime());
				}
			}

			if(m_MakePath->m_foundGoal == false && m_IsMovingSoldiers == true)
			{					
				m_MakePath->FindPath(D3DXVECTOR3(0, 3, 0), D3DXVECTOR3(0, 3, 0));
			}

			if(m_MakePath->m_foundGoal == true)
			{
				m_IsMovingSoldiers = false;

				for(int i = 0; m_Soldierlist.size() > i; ++i)
				{
					if(m_Soldierlist.at(i)->GetOpacity() == 0.5f)
					{
						m_AllSoldiersMoved = true;
						m_Soldierlist.at(i)->SetPath(m_MakePath->GetPath());
						m_Soldierlist.at(i)->m_GotPath = true;
						m_Soldierlist.at(i)->m_GotDestination = false;
					
					}
				}
				m_MakePath = new PathFinding(m_pLevel);
			}

			if(refInputState.IsKeyDown(VK_SPACE))
			{

			}			
	
			

			if(m_GotMain == false && m_Money < 4000)
			{
				m_EndScreen = new InterfaceItems(m_pContentManager, m_pD3DDevice, _T("./Effect/Interface.fx"), D3DXVECTOR2(-0.45, 0.15), 0.9, 0.3) ;
				m_EndScreen->Initialize(m_pContentManager);
	
				m_EndScreen->SetTexture(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/Defeat.jpg")));
				m_EndScreen->SetOpacity(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/Zero.jpg")));
				m_EndScreen->SetColor(true);

				m_TheEnd = true;
			}

			if(m_AI->GetIfDefeated() == true)
			{
				m_EndScreen = new InterfaceItems(m_pContentManager, m_pD3DDevice, _T("./Effect/Interface.fx"), D3DXVECTOR2(-0.45, 0.15), 0.9, 0.3) ;
				m_EndScreen->Initialize(m_pContentManager);
	
				m_EndScreen->SetTexture(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/Victory.jpg")));
				m_EndScreen->SetOpacity(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/Zero.jpg")));
				m_EndScreen->SetColor(true);

				m_TheEnd = true;
			}
		}
		//every levelElement assumes the pose that is calculated by the physics
		m_pLevel->Simulate(refInputState);
		m_pLevel->Tick(refInputState);
}

void EmptyApp::DrawScene()
{
	//Prepare to render
	m_pD3DDevice->ClearRenderTargetView(m_pRenderTargetView, m_ClearColor);
	m_pD3DDevice->ClearDepthStencilView(m_pDepthStencilView, D3D10_CLEAR_DEPTH|D3D10_CLEAR_STENCIL, 1.0f, 0);
	//wstring text;

	//after drawing text, the DepthStencilState has to be set
	

	m_pD3DDevice->OMSetDepthStencilState(0, 0);
	
	BaseCamera* activecam;

	//Get View and Projection from graphcamera
	if(m_iCameraNumber==1 && m_pGraphCamera)
	{
		activecam = m_pGraphCamera;
	}

	RenderContext renderContext(activecam, m_DirLight);
	RenderContext renderContextMini(m_MiniMapCamera, m_DirLight);
	

//if in debug mode, render normal and/or physics debug layer
#ifdef _DEBUG
	//Normal: no physics debugging is drawn
	if (m_renderstate == Normal )
	{	
		renderContext.SetShadowCamera(m_pShadowCam);
		renderContext.SetIsShadowMapping(false);

		m_PostProces->Begin();
		m_pLevel->Draw(&renderContext);
		m_PostProces->End();

		ResetRenderTarget(); // postrender

		m_FullScreenQuad->SetTexture(m_PostProces->GetColorMap());
		m_FullScreenQuad->SetColor(true);
		m_FullScreenQuad->Draw(&renderContext);

		m_Interface->Draw(&renderContext);

		for(int i = 0; m_HudItems.size() > i; ++i)
		{
			m_HudItems.at(i)->Draw(&renderContext);
		}

		if(m_TheEnd == true)
		{
			m_EndScreen->Draw(&renderContext);
		}

		m_SelectRect->Draw(&renderContext);

		m_PostProces->Begin();
		m_pLevel->Draw(&renderContextMini);	
		m_PostProces->End();

		ResetRenderTarget(); // postrender

		m_MiniMap->SetTexture(m_PostProces->GetColorMap());		
		m_MiniMap->Draw(&renderContextMini);
		
		tstringstream buffer;
		buffer << m_Money;
		buffer << " $";
		DrawString(m_pFont, buffer.str(), 950, 850);

		tstringstream buffer3;
		buffer3 << m_Soldierlist.size();
		buffer3 << " / ";
		buffer3 << m_MaxNumberSoldiers;
		buffer3 << " Soldiers";
		DrawString(m_pFont, buffer3.str(), 1100, 850);

		tstringstream buffer2;
		buffer2 << TestY;
		DrawString(m_pFont, buffer2.str(), 5, 5);
	
		if(m_BuildingSelected)
		{
			tstringstream buffer;
			buffer << m_Buildinglist.at(m_IdSelected)->GetLife();
			buffer << " / ";
			buffer << m_Buildinglist.at(m_IdSelected)->GetMaxLife();

			DrawString(m_pFont, buffer.str(), 950, 900);
		}

		m_pSwapChain->Present(0, 0);//Swaps front and backbuffer
		m_pLevel->FetchResults();//Waits until the Physics calcs are finished

	}
	//DebugPhysics: draw only physics debug
	if (m_renderstate == DebugPhysics )
	{
		// Draw Physics Debug as lines
		// Attention: Debug rendering can only be called when the physics calulations are done, and PhysX is idle
		renderContext.SetIsShadowMapping(false);
		m_pLevel->FetchResults();
		m_pPhysicsDebugRenderer->Draw(&renderContext);
		DrawString(m_pFont,  m_FrameStats.c_str(), 5,5);//draw statistics
		m_pSwapChain->Present(0, 0);//Swaps front and backbuffer
	}	
	//Both physics debug and output is drawn
	if(m_renderstate == MixedMode)
	{
		renderContext.SetIsShadowMapping(false);
		m_pLevel->FetchResults();
		m_pLevel->Draw(&renderContext);//Draws the scene
		m_pPhysicsDebugRenderer->Draw(&renderContext);
		DrawString(m_pFont,  m_FrameStats.c_str(), 5,5);//draw statistics
		m_pSwapChain->Present(0, 0);//Swaps front and backbuffer
	}


//in release mode, draw no physics
#else
	m_pLevel->Draw(&renderContext);
	DrawString(m_pFont,  m_FrameStats.c_str(), 5,5);//draw statistics
	m_pSwapChain->Present(0, 0);//swap front and backbuffer
	m_pLevel->FetchResults();
#endif
}
void EmptyApp::MessageProcedure(UINT message, WPARAM wParam, LPARAM lParam)
{
	
	switch( message )
	{
		case WM_KEYUP:
			switch (wParam)
			{
				case 'R':

					break;
				case 'C':


					break;

				case '1':
					
					break;

				case '2':
					
					break;

				case '3':
					
					break;

				case '4':
					break;
				case '5':
					break;
#ifdef _DEBUG
				// Toggle debug physics
				case 'P':
					if (m_renderstate == Normal)
					{
						tcout << _T("Mixed render mode\n");
						m_renderstate = MixedMode;
					}
					else if (m_renderstate == MixedMode)
					{
						tcout << _T("DebugPhysics render mode\n");
						m_renderstate = DebugPhysics;
					}
					else
					{
						tcout << _T("Normal render mode\n");
						m_renderstate = Normal;
					}
					break;
#endif
			}	
	}
}

void EmptyApp::EnterTriggerRegion()
{
	m_Triggered = true;
}

int EmptyApp::CalculateY(int x, int z)
{
	NxRay Raycast;

	Raycast.orig = NxVec3(x, 20, z);
	Raycast.dir = NxVec3(0, -1, 0);
	Raycast.dir.normalize();

	NxRaycastHit GetIntercect;

	NxShape* ClosestShape = m_pLevel->GetPhysicsScene()->raycastClosestShape(Raycast, NX_ALL_SHAPES, GetIntercect);

	if(ClosestShape)
	{
		return GetIntercect.worldImpact.y;
	}

	else return 0;
}

void EmptyApp::LoadMeshes()
{
	IniFile* config = new IniFile();
	config->SetValue(_T("Export"), _T("baseDir"), _T("./Resources/Models"));
	config->SetValue(_T("Export"), _T("meshDir"), _T("meshes"));
	config->SetValue(_T("Export"), _T("textureDir"), _T("textures"));

	LightReader lr (_T("./Resources/Models/meshes/lights.xml"));
	lr.Read();

	m_pShadowCam = new ShadowCamera(lr.GetLights().at(0), m_pD3DDevice);

	ObjReader reader(config,_T("level.obj"));
	bool success = reader.Read();
	if(success)
	{
		ObjMesh* TestModelMesh = reader.GetMesh(_T("Plane001"));
		DX10ObjMesh* dx10TestModel = new DX10ObjMesh(TestModelMesh);
		//dx10TestModel->Scale(D3DXVECTOR3(0.5,0.5,0.5));
		dx10TestModel->AddSpotLights(lr.GetLights());
		m_pLevel->AddChild(dx10TestModel);	
	}

	ObjReader reader7(config,_T("energy.obj"));
	success = reader7.Read();
	if(success)
	{
		ObjMesh* TestModelMesh = reader7.GetMesh(_T("energy"));
		Building* dx10TestModel = new Building(TestModelMesh, 2, 2, 2, 100, false, m_pContentManager);
		dx10TestModel->AddSpotLights(lr.GetLights());
		m_pLevel->AddChild(dx10TestModel);	
		m_Energylist.push_back(dx10TestModel);

		dx10TestModel = new Building(TestModelMesh, 2, 2, 2, 100, false, m_pContentManager);
		dx10TestModel->AddSpotLights(lr.GetLights());
		m_pLevel->AddChild(dx10TestModel);	
		m_Energylist.push_back(dx10TestModel);
	}

	PhysicsMesh* pMesh = new PhysicsMesh(_T("./Resources/Models/level.bin"), Concave, StaticObject);

	m_pLevel->AddChild(pMesh);

	ObjReader reader2(config,_T("tower.obj"));
	success = reader2.Read();
	if(success)
	{
		m_TowerMesh = reader2.GetMesh(_T("Box001"));
	}

	ObjReader reader3(config,_T("Harvester.obj"));
	success = reader3.Read();
	if(success)
	{
		m_HarvesterMesh = reader3.GetMesh(_T("Box001"));
	}

	ObjReader reader4(config,_T("House.obj"));
	success = reader4.Read();
	if(success)
	{
		m_HouseMesh = reader4.GetMesh(_T("house"));
	}

	ObjReader reader6(config,_T("Main.obj"));
	success = reader6.Read();
	if(success)
	{
		m_MainMesh = reader6.GetMesh(_T("Cylinder001"));
	}

	lr.Read();
	
	Building* build;
	build = new Building(m_MainMesh, 10, 15, 10, 1000, false, m_pContentManager);
	build->AddSpotLights(lr.GetLights());
	m_pLevel->AddChild(build);	

	//build->Initialize(m_pContentManager);
	build->SetNumber(1);
	m_Buildinglist.push_back(build);

	ObjReader reader5(config,_T("Barrack.obj"));
	success = reader5.Read();
	if(success)
	{
		m_BarracksMesh = reader5.GetMesh(_T("Box001"));
	}

	ObjMesh* EnemyMain, *EnemyHouse, *EnemyHarvester, *EnemyBarrack;

	ObjReader reader10(config,_T("Barrack2.obj"));
	success = reader10.Read();
	if(success)
	{
		EnemyBarrack = reader10.GetMesh(_T("Box001"));
	}

	ObjReader reader11(config,_T("Main2.obj"));
	success = reader11.Read();
	if(success)
	{
		EnemyMain = reader11.GetMesh(_T("Cylinder001"));
	}

	ObjReader reader12(config,_T("Harvester2.obj"));
	success = reader12.Read();
	if(success)
	{
		EnemyHarvester = reader12.GetMesh(_T("Box001"));
	}

	ObjReader reader13(config,_T("House2.obj"));
	success = reader13.Read();
	if(success)
	{
		EnemyHouse = reader13.GetMesh(_T("house"));
	}

	m_AI->Initialize(m_TowerMesh, EnemyHarvester, EnemyHouse, EnemyMain, EnemyBarrack);
}

void EmptyApp::LoadInterface()
{
	m_Interface = new Interface(m_pContentManager, m_pD3DDevice, _T("./Effect/Interface.fx"));
	m_Interface->Initialize(m_pContentManager);
	
	m_Interface->SetTexture(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/HUD.jpg")));
	m_Interface->SetOpacity(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/HUD_OP.jpg")));
	m_Interface->SetColor(true);

	InterfaceItems* Item = new InterfaceItems(m_pContentManager, m_pD3DDevice, _T("./Effect/Interface.fx"), D3DXVECTOR2(0.475f, -0.05f), 0.125f, 0.3f);
	Item->Initialize(m_pContentManager);
	Item->SetColor(true);
	Item->SetTexture(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/Main.jpg")));
	Item->SetOpacity(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/Zero.jpg")));

	m_HudItems.push_back(Item);

	Item = new InterfaceItems(m_pContentManager, m_pD3DDevice, _T("./Effect/Interface.fx"), D3DXVECTOR2(0.625f, -0.05f), 0.125f, 0.3f);
	Item->Initialize(m_pContentManager);
	Item->SetColor(true);
	Item->SetTexture(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/House.jpg")));
	Item->SetOpacity(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/Zero.jpg")));

	m_HudItems.push_back(Item);

	Item = new InterfaceItems(m_pContentManager, m_pD3DDevice, _T("./Effect/Interface.fx"), D3DXVECTOR2(0.775f, -0.05f), 0.125f, 0.3f);
	Item->Initialize(m_pContentManager);
	Item->SetColor(true);
	Item->SetTexture(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/Harvester.jpg")));
	Item->SetOpacity(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/Zero.jpg")));

	m_HudItems.push_back(Item);

	Item = new InterfaceItems(m_pContentManager, m_pD3DDevice, _T("./Effect/Interface.fx"), D3DXVECTOR2(0.475f, -0.375f), 0.125f, 0.3f);
	Item->Initialize(m_pContentManager);
	Item->SetColor(true);
	Item->SetTexture(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/Barrack.jpg")));
	Item->SetOpacity(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/Zero.jpg")));

	m_HudItems.push_back(Item);

	//Item = new InterfaceItems(m_pContentManager, m_pD3DDevice, _T("./Effect/Interface.fx"), D3DXVECTOR2(0.625f, -0.375f), 0.125f, 0.3f);
	//Item->Initialize(m_pContentManager);
	//Item->SetColor(true);
	//Item->SetTexture(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/KleineKogels.jpg")));
	//Item->SetOpacity(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/Zero.jpg")));

	//m_HudItems.push_back(Item);

	m_SelectRect = new InterfaceItems(m_pContentManager, m_pD3DDevice, _T("./Effect/Interface.fx"), D3DXVECTOR2(0, 0), 0.125f, 0.3f);
	m_SelectRect->Initialize(m_pContentManager);
	m_SelectRect->SetColor(true);
	m_SelectRect->SetTexture(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/Select.jpg")));
	m_SelectRect->SetOpacity(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/One.jpg")));
}

void EmptyApp::LeftMouse(const InputState & refInputState)
{
	POINTS Position = refInputState.GetMousePos();

	float Xndc = (float)(Position.x - (m_ClientWidth/2)) / (m_ClientWidth/2);
	float Yndc = (float)((m_ClientHeight/2) - Position.y) / (m_ClientHeight/2);

	if(Xndc > 0.336f && Yndc > 0.302f)
	{
			
	}

	else if(Xndc > 0.428f && Yndc < 0)
	{
		Building* build;
		PhysicsMesh* pMesh;
		bool IsHouse = false;

		if(Xndc > 0.475f && Yndc < -0.05f && Xndc < (0.475f  + BUTTONWIDTH) && Yndc > (-0.05f - BUTTONHEIGHT))
		{
			if(!(m_BuildingSelected == true && m_Buildinglist.at(m_IdSelected)->GetMesh() == m_BarracksMesh))
			{
				if(m_Money >= 4000)
				{
					build = new Building(m_MainMesh, 10, 15, 10, 1000, false, m_pContentManager);
					build->SetNumber(1);

					if(m_PlaceBuilding == true)
					{
						m_pLevel->RemoveChild(m_Buildinglist.back());
						m_Buildinglist.pop_back();			
					}

					m_PlaceBuilding = true;
					m_CostPrice = 4000;
				}
			}

			else
			{
				if(m_Money >= 200 && m_MaxNumberSoldiers > m_Soldierlist.size())
				{
					Soldier* SmallSoldier = new Soldier(_T("./Resources/Textures/KleineKogels.jpg"), 1, 15, 15, m_pContentManager, 50, 20, 2);					

					D3DXVECTOR4 pos;
					D3DXVec3Transform(&pos, &D3DXVECTOR3(0, 0, 0), &m_Buildinglist.at(m_IdSelected)->GetWorldMatrix());
					SmallSoldier->SetNumber(1);
					
					m_pLevel->AddChild(SmallSoldier);
					SmallSoldier->Initialize(m_pContentManager);
					SmallSoldier->Translate(D3DXVECTOR3(pos.x + 10, 3, pos.z));
					SmallSoldier->FindPosition();
					m_Soldierlist.push_back(SmallSoldier);

					m_Money -= 200;
				}
			}
		}

		if(Xndc > 0.625f && Yndc < -0.05f && Xndc < (0.625f  + BUTTONWIDTH) && Yndc > (-0.05f - BUTTONHEIGHT))
		{
			if(!(m_BuildingSelected == true && m_Buildinglist.at(m_IdSelected)->GetMesh() == m_BarracksMesh))
			{
				if(m_Money >= 500)
				{
					build = new Building(m_HouseMesh, 4, 3, 4, 200, false, m_pContentManager);
					build->SetNumber(1);

					if(m_PlaceBuilding == true)
					{
						m_pLevel->RemoveChild(m_Buildinglist.back());
						m_Buildinglist.pop_back();
					}

					m_PlaceBuilding = true;
					IsHouse = true;
					m_CostPrice = 500;
				}
			}

			else
			{
				if(m_Money >= 500 && m_MaxNumberSoldiers > m_Soldierlist.size())
				{
					Soldier* SmallSoldier = new Soldier(_T("./Resources/Textures/KleineKogels.jpg"), 3, 15, 15, m_pContentManager, 100, 35, 2);					

					D3DXVECTOR4 pos;
					D3DXVec3Transform(&pos, &D3DXVECTOR3(0, 0, 0), &m_Buildinglist.at(m_IdSelected)->GetWorldMatrix());
					SmallSoldier->SetNumber(1);
					
					m_pLevel->AddChild(SmallSoldier);
					SmallSoldier->Initialize(m_pContentManager);
					SmallSoldier->Translate(D3DXVECTOR3(pos.x + 10, 3, pos.z));
					SmallSoldier->FindPosition();
					m_Soldierlist.push_back(SmallSoldier);

					m_Money -= 500;
				}
			}
		}

		if(Xndc > 0.775f && Yndc < -0.05f && Xndc < (0.775f  + BUTTONWIDTH) && Yndc > (-0.05f - BUTTONHEIGHT))
		{
			if(!(m_BuildingSelected == true && m_Buildinglist.at(m_IdSelected)->GetMesh() == m_BarracksMesh))
			{
				if(m_Money >= 2000)
				{
					build = new Building(m_HarvesterMesh, 4, 9, 6.5, 400, false, m_pContentManager);
					build->SetNumber(1);

					if(m_PlaceBuilding == true)
					{
						m_pLevel->RemoveChild(m_Buildinglist.back());
						m_Buildinglist.pop_back();
					}

					m_PlaceBuilding = true;
					m_CostPrice = 2000;
				}
			}
		}

		if(Xndc > 0.475f && Yndc < -0.375f && Xndc < (0.475f  + BUTTONWIDTH) && Yndc > (-0.375f - BUTTONHEIGHT))
		{
			if(!(m_BuildingSelected == true && m_Buildinglist.at(m_IdSelected)->GetMesh() == m_BarracksMesh))
			{
				if(m_Money >= 2000)
				{
					build = new Building(m_BarracksMesh, 7, 6, 10, 400, false, m_pContentManager);
					build->SetNumber(1);

					if(m_PlaceBuilding == true)
					{
						m_pLevel->RemoveChild(m_Buildinglist.back());
						m_Buildinglist.pop_back();
					}
			
					m_PlaceBuilding = true;
					m_CostPrice = 2000;
				}
			}
		}

		//if(Xndc > 0.625f && Yndc < -0.375f && Xndc < (0.625f  + BUTTONWIDTH) && Yndc > (-0.375f - BUTTONHEIGHT))
		//{
		//	if(!(m_BuildingSelected == true && m_Buildinglist.at(m_IdSelected)->GetMesh() == m_BarracksMesh))
		//	{
		//		if(m_Money >= 1000)
		//		{
		//			build = new Building(m_TowerMesh, 2, 12, 2, 300, false, m_pContentManager);
		//			build->SetNumber(1);

		//			if(m_PlaceBuilding == true)
		//			{
		//				m_pLevel->RemoveChild(m_Buildinglist.back());
		//				m_Buildinglist.pop_back();
		//			}

		//			m_PlaceBuilding = true;
		//			m_CostPrice = 1000;
		//		}
		//	}
		//}

		if(m_PlaceBuilding == true)
		{			
			LightReader lr (_T("./Resources/Models/meshes/lights.xml"));
			lr.Read();

			build->AddSpotLights(lr.GetLights());
			m_pLevel->AddChild(build);	
			build->Initialize(m_pContentManager);
			if(IsHouse == true) build->Scale(D3DXVECTOR3(0.1f,0.1f,0.1f));
			else build->Scale(D3DXVECTOR3(0.2f,0.2f,0.2f));
			build->Translate(D3DXVECTOR3(D3DXVECTOR3(1000, 0, 1000)));
			build->SetTriggerPos(D3DXVECTOR3(D3DXVECTOR3(1000, 0, 1000)));
			m_Buildinglist.push_back(build);		
		}
	}

	else
	{
		if(m_PlaceBuilding == true)
		{
			bool IsNotPosible = false;
			int x = m_Buildinglist.back()->GetX();
			int y = m_Buildinglist.back()->GetY();
			int z = m_Buildinglist.back()->GetZ();

			D3DXVECTOR4 pos;
			D3DXVec3Transform(&pos, &D3DXVECTOR3(0, 0, 0), &m_Buildinglist.back()->GetWorldMatrix());

			if(pos.x <= -35 && pos.z <= -35)
			{

				NxRay Raycast;

				Raycast.orig = NxVec3(pos.x - x - 0.1f, 20, pos.z - z -0.1f);
				Raycast.dir = NxVec3(0, -1, 0);
				Raycast.dir.normalize();

				NxRaycastHit GetIntercect;

				NxShape* ClosestShape = m_pLevel->GetPhysicsScene()->raycastClosestShape(Raycast, NX_ALL_SHAPES, GetIntercect);

				if(ClosestShape)
				{
					if(GetIntercect.worldImpact.y > 0.2f) IsNotPosible = true;
				}


				Raycast.orig = NxVec3(pos.x - x - 0.1f, 20, pos.z + z + 0.1f);
				Raycast.dir = NxVec3(0, -1, 0);
				Raycast.dir.normalize();

				GetIntercect;

				ClosestShape = m_pLevel->GetPhysicsScene()->raycastClosestShape(Raycast, NX_ALL_SHAPES, GetIntercect);

				if(ClosestShape)
				{
					if(GetIntercect.worldImpact.y > 0.2f) IsNotPosible = true;
				}


				Raycast.orig = NxVec3(pos.x + x + 0.1f, 20, pos.z + z + 0.1f);
				Raycast.dir = NxVec3(0, -1, 0);
				Raycast.dir.normalize();

				GetIntercect;

				ClosestShape = m_pLevel->GetPhysicsScene()->raycastClosestShape(Raycast, NX_ALL_SHAPES, GetIntercect);

				if(ClosestShape)
				{
					if(GetIntercect.worldImpact.y > 0.2f) IsNotPosible = true;
				}


				Raycast.orig = NxVec3(pos.x + x + 0.1f, 20, pos.z - z - 0.1f);
				Raycast.dir = NxVec3(0, -1, 0);
				Raycast.dir.normalize();

				GetIntercect;

				ClosestShape = m_pLevel->GetPhysicsScene()->raycastClosestShape(Raycast, NX_ALL_SHAPES, GetIntercect);

				if(ClosestShape)
				{
					if(GetIntercect.worldImpact.y > 0.2f) IsNotPosible = true;
				}

				if(IsNotPosible == false) 
				{
					m_PlaceBuilding = false;

					m_Money -= m_CostPrice;

					D3DXVECTOR4 pos;
					D3DXVec3Transform(&pos, &D3DXVECTOR3(0, 0, 0), &m_Buildinglist.back()->GetWorldMatrix());

					m_Buildinglist.back()->SetTriggerPos(D3DXVECTOR3(pos.x, pos.y, pos.z));

					if(m_Buildinglist.back()->GetMesh() == m_HarvesterMesh)
					{
						D3DXVECTOR4 pos;
						D3DXVec3Transform(&pos, &D3DXVECTOR3(0, 0, 0), &m_Buildinglist.back()->GetWorldMatrix());

						//making new harvester
						m_TestSphere = new SpikeySphere(_T("./Resources/Textures/KleineKogels.jpg"));
						m_TestSphere->Translate(D3DXVECTOR3(pos.x, 3, pos.z - 8));
						m_TestSphere->m_PosHome = D3DXVECTOR3(pos.x, 3, pos.z - 8);
						m_TestSphere->SetOpacity(1);
						m_pLevel->AddChild(m_TestSphere);
						m_TestSphere->Initialize(m_pContentManager);
						m_Harvesterlist.push_back(m_TestSphere);

						//new harvester pathfinding
						PathFinding* path = new PathFinding(m_pLevel);
						m_HarvesterPathList.push_back(path);
					}

					if(m_Buildinglist.back()->GetMesh() == m_HouseMesh)
					{
						m_MaxNumberSoldiers += 3;
					}
				}
			}
		}

		else
		{
			for(int i = 0; m_Buildinglist.size() > i; ++i)
			{
				if(m_BuildingSelected == true && !(m_Buildinglist.at(m_IdSelected)->SeeIfSelected(m_pGraphCamera->GetViewProj(),Xndc, Yndc)))
				{
					m_BuildingSelected = false;

					if(m_Buildinglist.at(m_IdSelected)->m_ObjMesh == m_BarracksMesh)
					{
						m_HudItems.at(0)->SetTexture(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/Main.jpg")));
						m_HudItems.at(1)->SetTexture(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/House.jpg")));
						m_HudItems.at(2)->SetOpacity(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/Zero.jpg")));
						m_HudItems.at(3)->SetOpacity(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/Zero.jpg")));
						//m_HudItems.at(4)->SetOpacity(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/Zero.jpg")));
					}
				}

				if(m_Buildinglist.at(i)->SeeIfSelected(m_pGraphCamera->GetViewProj(), Xndc, Yndc))
				{
					m_BuildingSelected = true;
					m_IdSelected = i;

					if(m_Buildinglist.at(m_IdSelected)->m_ObjMesh == m_BarracksMesh)
					{
						m_HudItems.at(0)->SetTexture(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/Soldier.jpg")));
						m_HudItems.at(1)->SetTexture(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/Tank.jpg")));
						m_HudItems.at(2)->SetOpacity(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/one.jpg")));
						m_HudItems.at(3)->SetOpacity(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/one.jpg")));
						//m_HudItems.at(4)->SetOpacity(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/one.jpg")));
					}

					else
					{
						m_HudItems.at(2)->SetOpacity(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/Zero.jpg")));
						m_HudItems.at(3)->SetOpacity(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/Zero.jpg")));
						//m_HudItems.at(4)->SetOpacity(m_pContentManager->GetTexture(m_pLevel->GetDevice(), _T("./Resources/Textures/Zero.jpg")));
					}
				}				
			}
		}
	}
}

void EmptyApp::RightMouse(const InputState & refInputState)
{
	if(m_PlaceBuilding == true)
	{
		m_PlaceBuilding = false;
		m_Buildinglist.back()->RemoveThis();
		m_Buildinglist.pop_back();
	}


	POINTS Position = refInputState.GetMousePos();

	float Xndc = (float)(Position.x - (m_ClientWidth/2)) / (m_ClientWidth/2);
	float Yndc = (float)((m_ClientHeight/2) - Position.y) / (m_ClientHeight/2);
	D3DXMATRIX invers;
	D3DXMatrixInverse(&invers, NULL, &m_pGraphCamera->GetViewProj());

	D3DXVECTOR3 Nearplane(Xndc,Yndc, 0);
	D3DXVECTOR3 Farplane(Xndc, Yndc, 1);

	D3DXVECTOR3 NearplaneInv;
	D3DXVECTOR3 FarplaneInv;

	D3DXVec3TransformCoord(&NearplaneInv, &Nearplane, &invers);
	D3DXVec3TransformCoord(&FarplaneInv, &Farplane, &invers);

	NxVec3 direction(FarplaneInv.x - NearplaneInv.x, FarplaneInv.y - NearplaneInv.y, FarplaneInv.z - NearplaneInv.z);		

	NxRay Raycast;

	Raycast.orig = NxVec3(NearplaneInv.x, NearplaneInv.y, NearplaneInv.z);
	Raycast.dir = NxVec3(FarplaneInv.x, FarplaneInv.y, FarplaneInv.z) - NxVec3(NearplaneInv.x, NearplaneInv.y, NearplaneInv.z);
	Raycast.dir.normalize();

	NxRaycastHit GetIntercect;

	NxShape* ClosestShape = m_pLevel->GetPhysicsScene()->raycastClosestShape(Raycast, NX_ALL_SHAPES, GetIntercect);

	if(ClosestShape)
	{				
		if(GetIntercect.worldImpact.y < 0.2f)
		{
			m_TargetToAttack = NULL;

			m_MakePath = new PathFinding(m_pLevel);

			float MidX = 0;
			float MidZ = 0;
			float NumbersOf = 0;

			for(int i = 0; m_Soldierlist.size() > i; ++i)
			{
				if(m_Soldierlist.at(i)->GetOpacity() == 0.5f)
				{
					D3DXVECTOR4 pos;
					D3DXVec3Transform(&pos, &D3DXVECTOR3(0, 0, 0), &m_Soldierlist.at(i)->GetWorldMatrix());

					MidX += pos.x;
					MidZ += pos.z;

					++NumbersOf;
					m_Soldierlist.at(i)->StopAttacking();
				}
			}

			MidX /= NumbersOf;
			MidZ /= NumbersOf;

			if(NumbersOf !=0)
			{
				m_MakePath->FindPath(D3DXVECTOR3(MidX, 3, MidZ), D3DXVECTOR3(GetIntercect.worldImpact.x, 0, GetIntercect.worldImpact.z));

				m_IsMovingSoldiers = true;
			}
		}

		else
		{	
			m_TargetToAttack = NULL;

			vector<Building*> EnemyBuilding = m_AI->GetBuildingList();
			for(int i = 0; EnemyBuilding.size() > i; ++i)
			{
				if(EnemyBuilding.at(i)->SeeIfSelected(m_pGraphCamera->GetViewProj(),Xndc, Yndc))
				{
					m_TargetToAttack = EnemyBuilding.at(i);

					m_MakePath = new PathFinding(m_pLevel);

					float MidX = 0;
					float MidZ = 0;
					float NumbersOf = 0;

					for(int j = 0; m_Soldierlist.size() > j; ++j)
					{
						if(m_Soldierlist.at(j)->GetOpacity() == 0.5f)
						{
							D3DXVECTOR4 pos;
							D3DXVec3Transform(&pos, &D3DXVECTOR3(0, 0, 0), &m_Soldierlist.at(j)->GetWorldMatrix());

							MidX += pos.x;
							MidZ += pos.z;

							++NumbersOf;

							m_Soldierlist.at(j)->StopAttacking();
						}
					}

					MidX /= NumbersOf;
					MidZ /= NumbersOf;

					if(NumbersOf !=0)
					{
						D3DXVECTOR4 pos;
						D3DXVec3Transform(&pos, &D3DXVECTOR3(0, 0, 0), &EnemyBuilding.at(i)->GetWorldMatrix());

						
						m_MakePath->FindPath(D3DXVECTOR3(MidX, 3, MidZ), D3DXVECTOR3(pos.x - EnemyBuilding.at(i)->GetX() - 0.1f, 3, pos.z));

						m_IsMovingSoldiers = true;
					}
				}
			}
		}
	}	
}




